package com.uiotsoft.small.mqtt;

import com.uiotsoft.entity.MessageConvert;
import com.uiotsoft.entity.MessageWrapper;
import com.uiotsoft.small.config.APPConfig;
import com.uiotsoft.util.encrypt.small.SignUtil;
import com.uiotsoft.util.mqtt.MqttMessageUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * mqtt工具类
 */
@Data
@Slf4j
public class MqttClientOld {
    private String host;
    private String clientId;
    private MqttClient mqttClient;
    private String appKey;
    private String appSecret;
    private volatile String result;
    private volatile String topic;
    private volatile int dcCount = 0;

    public MqttClientOld(String host, String clientId) {
        this.host = host;
        this.clientId = clientId;
    }

    /**
     * mqttClient loginToCloud mqtt server
     */
    public void setMqttClient(MqttConnectOptions options, MqttCallback mqttCallback) throws MqttException {
        mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
        if (mqttCallback == null) {
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    log.debug("客户端连接丢失……,原因：{}", throwable.getStackTrace().toString());
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) {
                    MessageWrapper messageWrapper = MqttMessageUtil.getMessageData(mqttMessage.getPayload());
                    String appkey = messageWrapper.getAppkey();
                    log.debug("接收到的数据中appkey是：{}",appkey);
                    MessageConvert messageConvert;
                    if (appkey.equals(APPConfig.CHK_appKey)){
                        messageConvert =  MqttMessageUtil.decry(messageWrapper, APPConfig.CHK_appSecret);
                    }else {
                        messageConvert = MqttMessageUtil.decry(messageWrapper, appSecret);
                    }
                    result = messageConvert.getMessage().toJSONString();
                    topic = s;
                    log.debug("\n******收到服务返回的消息主题为：{}\n******数据为：{}",s,result);
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });
        } else {
            mqttClient.setCallback(mqttCallback);
        }
        mqttClient.connect(options);
    }

    public void close() {
        try {
            if (mqttClient != null) {
                mqttClient.disconnect();
                mqttClient.close();
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * mqttClient publish message default qos 1
     *
     * @param topic
     * @param send
     * @return
     * @throws MqttException
     */
    public boolean publish(String topic, byte[] send) {
        if (mqttClient.isConnected()){
            MqttTopic mqttTopic = mqttClient.getTopic(topic);
            try {
                MqttDeliveryToken token = mqttTopic.publish(send,0,false);
                token.waitForCompletion();
                return token.isComplete();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * mqttClient publish message default qos 1
     *
     * @param topic
     * @param msg
     * @return
     * @throws MqttException
     */
    public boolean publish(String topic, String msg) {

        byte[] send;
        if (topic.startsWith("common")){
            send = SignUtil.getPublishMessage(msg,APPConfig.CHK_appKey, APPConfig.CHK_appSecret);
        }else {
            send = SignUtil.getPublishMessage(msg,appKey, appSecret);
        }
        if (mqttClient.isConnected()){
            log.info("\n******客户端消息发布成功……\n******clientId：{}\n******topic：{}\n******content：{}",clientId,topic,msg);
            MqttTopic mqttTopic = mqttClient.getTopic(topic);
            try {
                MqttDeliveryToken token = mqttTopic.publish(send,0,false);
                token.waitForCompletion();
                return token.isComplete();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public boolean appPublish(String topic, String msg) {
        log.info("\n******客户端消息发布成功……\n******clientId：{}\n******topic：{}\n******content：{}",clientId,topic,msg);
        byte[] send = SignUtil.getPublishMessage(msg,appKey, appSecret);
        return publish(topic,send);
    }

    public boolean hostPublish(String topic, String msg) {
        log.info("\n******客户端消息发布成功……\n******clientId：{}\n******topic：{}\n******content：{}",clientId,topic,msg);
        byte[] send;
        if (topic.startsWith("common")){
            send = SignUtil.getPublishMessage(msg,APPConfig.CHK_appKey, APPConfig.CHK_appSecret);
        }else {
            send = SignUtil.getPublishMessage(msg,appKey, appSecret);
        }
        return publish(topic,send);
    }
    /**
     * mqttClient subscribe topic default qos 1
     *
     * @param topic
     * @throws MqttException
     */
    public void subscribe(String topic) {
        try {
            mqttClient.subscribe(topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * mqttClient subscribe topic with qos
     *
     * @param topic
     * @param qos
     * @throws MqttException
     */
    public void subscribe(String topic, int qos) throws MqttException {
        mqttClient.subscribe(topic, qos);
    }
}
